﻿using System;
using System.Xml;
using System.Windows.Forms;

namespace Vwlab
{
    public class Api
    {
        #region Settings api
        public static string[] opt = new string[6] {
            "2382059", 
            "api.vk.com", 
            "audio,friends,message,offline",
            "blank.html",
            "page",
            "token"
        };

        private Random r = new Random();
        private XmlDocument xmlDoc = new XmlDocument();
        Error err = new Error();
        #endregion

        #region functions
        public string AccessToken
        {
            get { return accesstoken; }
            set { accesstoken = value; }
        }
        private string accesstoken = "";

        public int UserID
        {
            get { return userid; }
            set { userid = value; }
        }
        private int userid = -1;

        public int homeUserID
        {
            get { return homeuserid; }
            set { homeuserid = value; }
        }
        private int homeuserid = -1;

        public int Timestamp
        {
            get { return (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds; }
            set { timestamp = value; }
        }
        private int timestamp;

        public int Random
        {
            get { return r.Next(1000, 9999); }
            set { random = value; }
        }
        private int random;

        public Uri urlLogin
        {
            get { return new Uri("http://" + opt[1] + "/oauth/authorize?client_id=" + opt[0] + "&scope=" + opt[2] + "&redirect_uri=http://" + opt[1] + "/" + opt[3] + "&display=" + opt[4] + "&response_type=" + opt[5]); }
            set { urllogin = value; }
        }
        private Uri urllogin;

        public Uri urlLogout
        {
            get { return new Uri("http://" + opt[1] + "/oauth/logout/?success_url=client_id=" + opt[0] + "&scope=" + opt[2] + "&redirect_uri=http://" + opt[1] + "/" + opt[3] + "&display=" + opt[4] + "&response_type=" + opt[5]); }
            set { urllogout = value; }
        }
        private Uri urllogout;
        #endregion

        /**
         * method - audio.get
         * elem - audio / разборка XML, тоесть мы получаем список тегов audio, а уже из него получаем aid, url И прочее
         * fields - new string[]{"aid", "url"} / то какие данные мы хотим получить
         * param - new string[,] {{"uid", "123456789"}} / отправляем запрос, что сделать выборку либо другие действия
         * 
         * Методы: http://vk.com/developers.php?o=-1&p=Описание+методов+API
         * Расширенные методы: http://vk.com/developers.php?o=-1&p=Расширенные+методы+API
         */
        #region getApi
        public Array[] getApi(string method, string elem, string[] fields = null, string[,] param = null)
        {
            #region Fields
            string fieldsString = "";
            if (fields != null)
            {
                fieldsString = "fields=";
                for (int i = 0; i < fields.Length; i++)
                {
                    fieldsString += fields[i] + ",";
                }
                fieldsString = fieldsString.Substring(0, fieldsString.Length - 1)+"&";
            }
            #endregion

            #region Parameters
            string paramString = "";
            if (param != null)
            {
                for (int i = 0; i < param.Length / 2; i++)
                {
                    paramString += param[i, 0] + "=" + param[i, 1] + "&";
                }
            }

            #endregion

            try
            {
                xmlDoc.Load("https://" + opt[1] + "/method/" + method + ".xml?" + fieldsString + paramString + "access_token=" + this.AccessToken + "&timestamp=" + this.Timestamp + "&random=" + this.Random);
            }
            catch(Exception)
            {
                err.setError("Ошибка при получении данных");
            }

            XmlNodeList xmlLists = xmlDoc.GetElementsByTagName(elem);

            
                Array[] result = new Array[xmlLists.Count];
            if (fields != null)
            {
                for (int i = 0; i < xmlLists.Count; i++)
                {
                    string[] content = new string[fields.Length];

                    for (int p = 0; p < fields.Length; p++)
                    {
                        try
                        {
                            content[p] = xmlDoc.GetElementsByTagName(fields[p])[i].InnerText;
                        }
                        catch (Exception e)
                        {
                            err.setError(e.Message);
                        }
                    }

                    result[i] = content;
                }

                return result;
            }
            else
            {
                result[0] = new string[1] {xmlDoc.GetElementsByTagName(elem)[0].InnerText};
                return result;
            }
        }
        #endregion
    }
}
